import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@views/Home'
import { isLogin } from '@utils/isLogin'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    meta: {
      needlogin: false,
      keepAlive: true
    }
  },
  {
    path: '/about',
    component: () => import('@views/About'),
    meta: {
      needlogin: true
    }
  },
  {
    path: '/cate',
    component: () => import('@views/Cate'),
    meta: {
      needlogin: false
    }
  },
  {
    path: '/cart',
    component: () => import('@views/Cart'),
    meta: {
      needlogin: true
    }
  },
  {
    path: '/itemlist',
    component: () => import('@views/ItemList'),
    meta: {
      needlogin: false
    }
  },
  {
    path: '/detail/:id',
    component: () => import('@views/Detail'),
    meta: {
      needlogin: false
    }
  },
  {
    path: '/login',
    component: () => import('@views/Login'),
    meta: {
      needlogin: false
    }
  },
  {
    path: '/register',
    component: () => import('@views/Register'),
    meta: {
      needlogin: false
    }
  },
  {
    path: '/contactadd',
    component: () => import('@views/ContactAdd'),
    meta: {
      needlogin: true
    }
  },
  {
    path: '/contactlist',
    component: () => import('@views/ContactList'),
    meta: {
      needlogin: true
    }
  },
  {
    path: '/contactupdate',
    component: () => import('@views/ContactUpdate'),
    meta: {
      needlogin: true
    }
  },
  {
    path: '/commitorder',
    component: () => import('@views/CommitOrder'),
    meta: {
      needlogin: true
    }
  },
  {
    path: '/search',
    component: () => import('@views/Search'),
    meta: {
      needlogin: false
    }
  },
  {
    path: '/searchresult',
    component: () => import('@views/SearchResult'),
    meta: {
      needlogin: false
    }
  },
  {
    path: '*',
    component: () => import('@views/undefined')
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 如果此路由需要登录
  if (to.meta.needlogin) {
    // 如果当前有token 引入isLogin方法
    if (isLogin()) {
      // 有 放行
      next()
    } else {
      // 没有 跳转至登录 并传递跳转前得地址 方便登录后调回
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
    // 不需要登录 直接放行
  } else {
    next()
  }
})
export default router
